<?php if (!defined("BASEPATH")) exit("No direct script access allowed");

class Messages extends MY_Controller {

	function __construct() {

		parent::__construct();
		if(!$this->session->userdata("usrId")) {
			redirect("");
			exit(0);
		}
		$this->load->model("message");
		$this->db->cache_off();
	}

	function _remap($param, $args) {
		if(method_exists($this, $param)) {
			$this->$param((isset($args[0]))?($args[0]):(NULL));
		} else {
			$this->load->model("usr2ent");
			$getUsr2ent = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."'");
			$getUsr2entINS = (($getUsr2ent and isset($getUsr2ent["INS"]))?($getUsr2ent["INS"]["children"]):(array()));
			//Common::pr($_POST); Common::pr($_FILES); exit;
			if(($this->input->post("subject") or $this->input->post("uniqueId")) and $this->input->post("message") and $this->input->post("insId")) {
				$mes_unique_id = (($this->input->post("uniqueId"))?($this->input->post("uniqueId")):($this->message->getUniqueId()));
				$mes_file_name_original = NULL;
				$mes_file_name = NULL;

				//Common::pr($_POST); Common::pr($_FILES); exit;
				if(count($_FILES) and isset($_FILES[key($_FILES)]["name"]) and $_FILES[key($_FILES)]["name"]) {
					$response["error"] = "";
					$save_path = $_SERVER["DOCUMENT_ROOT"].str_replace("media", "uploads", MEDIA);
					$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';
					$MAX_FILENAME_LENGTH = 260;

					$max_file_size_in_bytes = 2147483647; // 2GB in bytes
					$upload_name = key($_FILES);

					$POST_MAX_SIZE = ini_get('post_max_size');
					$unit = strtoupper(substr($POST_MAX_SIZE, -1));
					$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

					if((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
						$response["error"] .= $this->lang->line("POST_EXCEEDED_MAXIMUM_ALLOWED_SIZE")."<br/>";
					}

					// Other variables
					$file_name = '';
					$uploadErrors = array(
						0 => $this->lang->line("THERE_IS_NO_ERROR_THE_FILE_UPLOADED_WITH_SUCCESS"),
						1 => $this->lang->line("THE_UPLOADED_FILE_EXCEEDS_THE_UPLOAD_MAX_FILESIZE_DIRECTIVE"),
						2 => $this->lang->line("THE_UPLOADED_FILE_EXCEEDS_THE_MAX_FILE_SIZE_DIRECTIVE_THAT_WAS_SPECIFIED_IN_THE_HTML_FORM"),
						3 => $this->lang->line("THE_UPLOADED_FILE_WAS_ONLY_PARTIALLY_UPLOADED"),
						4 => $this->lang->line("NO_FILE_WAS_UPLOADED"),
						6 => $this->lang->line("MISSING_A_TEMPORARY_FOLDER")
					);

					// Validate the upload
					if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
						$response["error"] .= $uploadErrors[$_FILES[$upload_name]["error"]]."<br/>";
					} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
						$response["error"] .= $this->lang->line("UPLOAD_FAILED_IS_UPLOADED_FILE_TEST")."<br/>";
					} else if (!isset($_FILES[$upload_name]['name'])) {
						$response["error"] .= $this->lang->line("FILE_HAS_NO_NAME")."<br/>";
					}

					// Validate the file size (Warning: the largest files supported by this code is 2GB)
					$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
					if (!$file_size || $file_size > $max_file_size_in_bytes) {
						$response["error"] .= $this->lang->line("FILE_EXCEEDS_THE_MAXIMUM_ALLOWED_SIZE")."<br/>";
					}

					if ($file_size <= 0) {
						$response["error"] .= $this->lang->line("FILE_SIZE_OUTSIDE_ALLOWED_LOWER_BOUND")."<br/>";
					}

					$rand = mt_rand()."_".uniqid("", TRUE);

					$path_info = pathinfo($_FILES[$upload_name]["name"]);
					$file_extension = $path_info["extension"];

					$mes_file_name = $mes_unique_id."_".$rand.".".$file_extension;
					$mes_file_name_original = basename($_FILES[$upload_name]['name']);
					@copy($_FILES[$upload_name]['tmp_name'], $save_path.$mes_file_name);
				}
			
				/*
				if(count($getUsr2entINS) and in_array($this->input->post("insId"), $getUsr2entINS)) {
					$mes_usr_id = NULL;
					$mes_ins_usr_id = $this->session->userdata("usrId");
				} else {
					$mes_usr_id = $this->session->userdata("usrId");
					$mes_ins_usr_id = NULL;
				}
				*/
				
				if($this->input->post("mesId") and $this->message->checkMesId("(mes_id = '".intval($this->input->post("mesId"))."' and (mes_sender_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."' ".((count($getUsr2entINS))?(" or mes_ins_id in (".implode(",", $getUsr2entINS).")"):(""))." ))")) {
					$upd = array(
						"mes_message" => $this->input->post("message"),
					);
					if($mes_file_name) {
						$upd["mes_file_name"] = $mes_file_name;
						$upd["mes_file_name_original"] = $mes_file_name_original;
					}
					$this->message->update($this->input->post("mesId"), $upd);
				} else {
				
					$this->message->insert(
						array(
							"mes_sender_usr_id" => $this->session->userdata("usrId"),
							"mes_ins_id" => $this->input->post("insId"),
							//"mes_ins_usr_id" => $mes_ins_usr_id,
							"mes_unique_id" => $mes_unique_id,
							"mes_subject" => $this->input->post("subject"),
							"mes_message" => $this->input->post("message"),
							"mes_file_name" => $mes_file_name,
							"mes_file_name_original" => $mes_file_name_original,
							"mes_createdate" => Common::now(),
						)
					);
					
					// email kuldes
					$this->load->model("usr2ent");
					$where = "u2e_ins_id = '".intval($this->input->post("insId"))."' and u2e_page_cat = 'IMP'";
					$getUserList2Ent = $this->usr2ent->getUserList2Ent($where);
					$admin = FALSE;
					foreach($getUserList2Ent as $usrEmail => $usrName) {
						if($usrEmail == $this->session->userdata("usrEmail")) {
							$admin = TRUE;
						}
					}
					$this->load->model("user");
					if($admin) {
						$getFirstSender = $this->message->getFirstSender($mes_unique_id);
						if($getFirstSender) {
							$getUser = $this->user->getSingleUser("usr_email = '".$this->db->escape_str($getFirstSender)."'");
							if(count($getUser)) {
								$usrId = key($getUser);
								Common::sendEmail($getUser[$usrId]["usrEmail"], $this->lang->line("NEW_MESSAGE_ARRIVED_EMAIL_SUBJECT"), $this->lang->line("NEW_MESSAGE_ARRIVED_EMAIL_BODY"), $replace = array("<FULL_NAME>" => (($getUser[$usrId]["fullName"])?($getUser[$usrId]["fullName"]):($getUser[$usrId]["usrEmail"])), "<SENDER_FULL_NAME>" => (($this->session->userdata("fullName"))?($this->session->userdata("fullName")):($this->session->userdata("usrEmail")))), $attach = NULL);
							}
						}
					} else {
						foreach($getUserList2Ent as $usrEmail => $usrName) {
							$getUser = $this->user->getSingleUser("usr_email = '".$this->db->escape_str($usrEmail)."'");
							if(count($getUser)) {
								$usrId = key($getUser);
								Common::sendEmail($usrEmail, $this->lang->line("NEW_MESSAGE_ARRIVED_EMAIL_SUBJECT"), $this->lang->line("NEW_MESSAGE_ARRIVED_EMAIL_BODY"), $replace = array("<FULL_NAME>" => (($getUser[$usrId]["fullName"])?($getUser[$usrId]["fullName"]):($getUser[$usrId]["usrEmail"])), "<SENDER_FULL_NAME>" => (($this->session->userdata("fullName"))?($this->session->userdata("fullName")):($this->session->userdata("usrEmail")))), $attach = NULL);
							}
						}
					}
				}
				
			}

			$params = $this->_sidebar();
			$params["breadcrumbs"] = array(
				site_url() => $this->lang->line("HOME"),
				$this->lang->line("MESSAGES")
			);
			$params["title"] = $this->lang->line("MESSAGES");
			
			$params["now"] = Common::now();
			$params["getMessage"] = $this->message->getMessage($where = "(mes_sender_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."' ".((count($getUsr2entINS))?(" or mes_ins_id in (".implode(",", $getUsr2entINS).")"):(""))." )");
			
			// readdate karbantartas
			
			foreach($params["getMessage"] as $messages) {
				foreach($messages as $message) {
					if(!$message["mesReaderUsrId"] and $message["mesSenderUsrId"] != $this->session->userdata("usrId")) {
						$this->message->update($message["mesId"],
							array(
								"mes_reader_usr_id" => $this->session->userdata("usrId"),
								"mes_readdate" => $params["now"],
							) 
						);
					}
				}
			}

			if($this->input->is_ajax_request()) {
				echo json_encode(array("success" => true, "error" => ""));
			} elseif($this->input->get_post("admin")) {
				//echo json_encode(array("success" => true, "error" => ""));
				$this->db->query("commit");
				redirect("admin_lte/messages/".$this->input->post("uniqueId"));
			} else {
				$params["content"] = $this->load->view("messages/index", $params, TRUE);

				$this->load->view("template/page", $params);
			}
			
		}
	}

	function _sidebar() {
		$this->load->model("article_model");
		$params["getTags"] = $this->article_model->getTags();
		$params["sidebar"] = $this->load->view("page/sidebar", $params, TRUE);
		return $params;
	}

	function download($mes_file_name = NULL) {
		$this->load->model("message");
		
		$this->load->model("usr2ent");
		$getUsr2ent = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."'");
		$getUsr2entINS = (($getUsr2ent and isset($getUsr2ent["INS"]))?($getUsr2ent["INS"]["children"]):(array()));
		
		$where = "mes_file_name = '".$this->db->escape_str($mes_file_name)."' ".((Common::isSuperAdmin())?(""):(" and (mes_sender_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."' ".((count($getUsr2entINS))?(" or mes_ins_id in (".implode(",", $getUsr2entINS).")"):("")).")"))." ";
		$getFileNameOriginalByFileName = $this->message->getFileNameOriginalByFileName($where);
		$save_path = $_SERVER["DOCUMENT_ROOT"].str_replace("media", "uploads", MEDIA);
		if($getFileNameOriginalByFileName and is_file($save_path.$mes_file_name)) {
			$this->load->helper("download");
			$data = file_get_contents($save_path.$mes_file_name);
			force_download($getFileNameOriginalByFileName, $data); 
		}
		exit;
		redirect("");
	}
	
	function message_insert_update() {
		if($this->input->get_post("del")) {
			$this->load->model("message");
			
			$this->load->model("usr2ent");
			$getUsr2ent = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."'");
			$getUsr2entINS = (($getUsr2ent and isset($getUsr2ent["INS"]))?($getUsr2ent["INS"]["children"]):(array()));
			
			$getMessage = $this->message->getMessage("(mes_id = '".intval($this->input->get_post("mesId"))."' and (mes_sender_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."' ".((count($getUsr2entINS))?(" or mes_ins_id in (".implode(",", $getUsr2entINS).")"):(""))." ))");
			if(Common::isSuperAdmin() or count($getMessage)) {
				$this->message->delete($this->input->get_post("mesId"));
			}

		}
	}

}